package com.hbfec.fileserver.service;

import com.hbfec.fileserver.pojo.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 数据库 Service
 */
@Service
public class DbService {
    // 根据uuid和status查询文件信息
    private static final String QUERY_FILE_WITH_UUID_AND_STATUS =
            "SELECT uuid,url,name,size,createdate,expire,status FROM tb_file WHERE uuid=? AND status=?";
    // 添加或更新一条文件信息
    private static final String REPLACE_FILE =
            "REPLACE INTO tb_file(uuid,url,name,size,createdate,expire,status) VALUES(?,?,?,?,?,?,?)";

    @Autowired
    @Qualifier("persistJdbcTemplate")
    private JdbcTemplate persistJdbcTemplate;
    @Autowired
    @Qualifier("businessJdbcTemplate")
    private JdbcTemplate businessJdbcTemplate;

    /**
     * 根据uuid和status，获取文件的全部信息
     *
     * @param uuid   uuid
     * @param status status
     * @return 文件信息
     * @throws EmptyResultDataAccessException 查询结果为空，则抛出该异常
     */
    public Map<String, Object> queryFileWithUuidAndStatus(String uuid,
                                                          String status) throws EmptyResultDataAccessException {
        return businessJdbcTemplate.queryForMap(QUERY_FILE_WITH_UUID_AND_STATUS, uuid, status);
    }

    /**
     * 更新文件信息
     *
     * @param replacedFiles 文件信息
     */
    @Transactional
    public void updateFile(final List<File> replacedFiles) {
        if (!replacedFiles.isEmpty()) {
            persistJdbcTemplate.batchUpdate(REPLACE_FILE, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                    preparedStatement.setString(1, replacedFiles.get(i).getUuid());
                    preparedStatement.setString(2, replacedFiles.get(i).getUrl());
                    preparedStatement.setString(3, replacedFiles.get(i).getName());
                    preparedStatement.setLong(4, replacedFiles.get(i).getSize());
                    preparedStatement.setTimestamp(5,
                            new java.sql.Timestamp(replacedFiles.get(i).getCreateDate().getTime()));
                    preparedStatement.setString(6, replacedFiles.get(i).getExpire());
                    preparedStatement.setString(7, replacedFiles.get(i).getStatus());
                }

                @Override
                public int getBatchSize() {
                    return replacedFiles.size();
                }
            });
        }
    }
}
